package com.littora.alarm;

import com.littora.alarm.config.ConfigProperties;
import com.littora.alarm.email.EmailSender;
import com.littora.alarm.utils.FileUtils;
import com.littora.alarm.watch.FileMonitor;
import com.littora.alarm.watch.FileStatusCallback;

import java.io.File;
import java.io.IOException;


public class AlarmWatchMain {
    private ConfigProperties config;
//    private DirObserver dirObserver;
    private FileMonitor fileMonitor;
    private EmailSender emailSender;
    private String lastLog = "";

    public AlarmWatchMain() throws IOException {
        config = new ConfigProperties();
        fileMonitor = new FileMonitor(1000);
        emailSender = new EmailSender(config.getEmailToken());
    }

    public void watchNatappLog() {
        fileMonitor.monitor(config.getFileDir(),file->file.getName().endsWith(".log"),(file,status)->{
            if(status == FileStatusCallback.MODIFY || status == FileStatusCallback.CREATE) {
                try {
                    String result = FileUtils.findKeywork(config.getFileDir() + File.separator + file.getName(),config.getFileKeywork());
                    if (!"".equals(result) && !lastLog.equals(result)) {
                        emailSender.sendQQEmail(config.getEmailFrom(),config.getEmailTo(),result,result);
                        lastLog = result;
                        FileUtils.cleanLog(config.getFileDir());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        try {
            fileMonitor.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws IOException {
        AlarmWatchMain main = new AlarmWatchMain();
        main.watchNatappLog();
    }
}
